const { ref } = Vue
import { useFetch } from '../../../Scripts/hooks/useFetch.js'
const { ElMessage, ElMessageBox } = ElementPlus

export function useResourceStatusMaint() {
  let resourceStatusMaintDialogVisible = ref(false);
  let resourceStatus = ref('开机');
  let resourceStatusList = ref([]);
  let resourceStatusListRef = ref();

  const getResourceStatusListData = async configObj => {
    const { data } = await useFetch({
      url: `${configObj.url}?actions=${configObj.method}`,
      data: {
        type: `${configObj.method}`,
        employeeid: configObj.employeeid,
      }
    });
    resourceStatusList.value = data.value;
  };

  const setResourceStatus = async configObj => {
    const { data } = await useFetch({
      url: `${configObj.url}?actions=${configObj.method}`,
      data: {
        type: `${configObj.method}`,
        postData: configObj.postData,
      }
    });
    return data.value;
  };

  const resourceStatusConfirm = configObj => {
    const selectRows = resourceStatusListRef.value.getSelectionRows();
    if (selectRows.length === 0) {
      return ElMessage({ type: 'error', message: `请选择要录入的设备`, grouping: true });
    }

    ElMessageBox.confirm(`确认要将所选设备状态设置为【${resourceStatus.value}】吗?`, '确认', { type: 'warning' }).then(async () => {
      const postData = [];
      for (const i of selectRows) {
        postData.push({
          Workerid: configObj.employeeid,
          Resourceid: i.resourceid,
          Resourcestatus: resourceStatus.value
        });
      }
      const res = setResourceStatus({ url: configObj.url, method: 'setResourceStatus', postData });
      if (res) {
        ElMessage({ type: 'success', message: '录入成功' });
      }
      resourceStatusMaintDialogVisible.value = false;
    }).catch(() => {
      ElMessage({ type: 'info', message: '已取消录入' });
    });
  }

  return {
    resourceStatusMaintDialogVisible, resourceStatus, resourceStatusList, resourceStatusListRef,
    getResourceStatusListData, setResourceStatus, resourceStatusConfirm
  };
}